<%
# Group by date and sort Issues.
issues_by_due_date = issues.group_by(&:due_date)
keys = issues_by_due_date.keys
if keys.include?(nil) then
	keys.delete(nil)
	keys.sort!
	keys.push(nil)
else
	keys.sort!
end

# Get issue spent hours.
issues_spent_hours = Hash.new
issues.each do |issue|
	issues_spent_hours[issue.id] = issue.spent_hours
end

# Group by date Time Entries.
entries_by_date = entries.group_by(&:spent_on)
%>

<tr>
	<th>
		<%= user_name %>
	</th>
	<% for now_date in date_from .. date_to do %>
	<td>
		<table class="how_busy_timelog">
			<%
				now_spent_hours = 0

				# Print past Time Entries.
				if now_date <= Date.today && entries_by_date[now_date] != nil then
					entries_by_date[now_date].each do |entry|
			%>
			<%= render :partial => 'how_busy/entry.rhtml', :locals => {
				:type => "past_work",
				:issue => entry.issue,
				:hours => entry.hours } %>
			<%
					now_spent_hours += entry.hours
					end
				end

				flag = true
				# If past days, no print future Time Entries.
				if now_date < Date.today then flag = false end

				# If not weekday, no print future Time Entries.
				if now_date.wday == 0 || now_date.wday == 6 then flag = false end

				if flag then
					keys.each do |date|
						issues_by_due_date[date].each do |issue|
							issue_rest_hours = issue.estimated_hours.to_f - issues_spent_hours[issue.id]
							if issue_rest_hours <= 0 then next
							elsif now_spent_hours >= regular_work_hours && (date == nil || date > now_date) then next
							elsif issue.start_date != nil && now_date < issue.start_date then next
							elsif issue_rest_hours <= regular_work_hours - now_spent_hours then
			%>
			<%= render :partial => 'how_busy/entry.rhtml', :locals => {
				:type => "regular_work",
				:issue => issue,
				:hours => issue_rest_hours } %>
			<%
								issues_spent_hours[issue.id] += issue_rest_hours
								now_spent_hours += issue_rest_hours
							elsif date != nil && date <= now_date then
			%>
			<%= render :partial => 'how_busy/entry.rhtml', :locals => {
				:type => "over_work",
				:issue => issue,
				:hours => issue_rest_hours } %>
			<%
								issues_spent_hours[issue.id] += issue_rest_hours
								now_spent_hours += issue_rest_hours
							else
			%>
			<%= render :partial => 'how_busy/entry.rhtml', :locals => {
				:type => "regular_work",
				:issue => issue,
				:hours => regular_work_hours - now_spent_hours } %>
			<%
								issues_spent_hours[issue.id] += regular_work_hours - now_spent_hours
								now_spent_hours += regular_work_hours - now_spent_hours
							end
						end
					end
				end
			%>
		</table>
	</td>
	<% end %>
</tr>
